import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Dimensions,
  NativeAppEventEmitter,
  DeviceEventEmitter,
  AppState,
  InteractionManager,
} from 'react-native';

import styles from './indexStyle';
import CustomListView from '../global/CustomListView';
import ListViewActivityIndicator from '../global/ListViewActivityIndicator';
import api from '../../services/api';
import _ from 'lodash';
import SocketIO from 'react-native-socketio';
import Toast from 'react-native-sk-toast';
import * as config from '../../constants/apiConfig';
import JPushModule from 'jpush-react-native';
import Touch from '../global/Touch';

const {width: deviceWidth, height: deviceHeight} = Dimensions.get('window');

class indexList extends Component {
    constructor(props) {
		super(props);

		this.state = {
			currentPage: 1,
            noData: false,
            unreadMess:{}
		};

        // this._page = 0;
        this.totalpage = 0;
        this.pagesize = 400;
        this.unreadMess = {};
        this.list = [];

        if(Platform.OS == 'ios'){//收到推送
             this.subscription = NativeAppEventEmitter.addListener(
                'OpenNotification',
                async(notification)=>{
                    let res = await api.post("/housekeeper/findOwnerByOpenId",{openid:notification.openid});
                    if(res.data){
                        this._fireMessage(res.data);
                    }
                });
        }else{
            JPushModule.notifyJSDidLoad();
            JPushModule.addReceiveOpenNotificationListener(async(map)=>{

                var extra = JSON.parse(map.extras);
                let res = await api.post("/housekeeper/findOwnerByOpenId",{openid:extra.openid});
                if(res.data){
                    this._fireMessage(res.data);
                }
            });
        }

        this.socket = new SocketIO(config.SOCKET_URL, {});

        AppState.addEventListener('change', this._handleAppStateChange.bind(this));

		this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    async setRomteState(appState){
        let {session} = this.props;
        await api.post("/housekeeper/modifyAppState",{id: session && session.user.id, state: appState});
    }

    _handleAppStateChange(appState){
        this.setRomteState(appState);
    }

    _onNavigatorEvent(event){
        // console.log("###", event);
        if(event.id == "didAppear"){
            //清空角标
            if(Platform.OS == 'ios'){
                JPushModule.setBadge(0,(success)=>{});
            }

        }

        if (event.type == 'NavBarButtonPress') {
              if (event.id == 'search') {
                //   this.searchHeader.show();
                this.props.navigator.push({
                    title: "搜索",
                    backButtonTitle:'',
                    screen: 'housekeeperapp.searchlist',
                    passProps: {

                    },
                    navigatorStyle:{
                        navBarHidden: true,
                        tabBarHidden: true,
                        navBarTextColor: 'white',
                        navBarButtonColor: 'white',
                        navBarBackgroundColor: '#EA5404',
                        navBarTitleTextCentered: true,
                        topBarElevationShadowEnabled:false,
                        statusBarColor: '#EA5404'
                    },
                    // backButtonHidden: true,
                });
              }
        }
    }

    async upDateView(message){
        if(!message || !message.user){
            return;
        }

        var userInfo = _.filter(this.list, function(o) { return o.wxOpenId == message.user._id; });
        // console.log("########", userInfo);

        if(userInfo && userInfo.length > 0){//如果是本人
            message.user.avatar = userInfo[0].wxHeader;
            let messageArr = [];
            let {actions, dispatch, global} = this.props;

            if(!global.is_enter_message){//没有进入消息会话界面
                //每个列表更新
                let index = _.findIndex(this.list, function(o) { return o.wxOpenId == message.user._id; });

                const newList = this.list.map((a, i_index) => {
                  //make a copy of the this.list. Otherwise you'll be modifying
                  //an object that's in your listView's datasource,
                  //and therefore frozen.
                  let copyA = {...a};
                  if (i_index == index){
                    copyA.unread = true;
                  }

                  return copyA;
                });
                this.unreadMess[index]++;

                // this.setState({
                //     unreadMess: this.unreadMess
                // });

                // console.log("####！！！", newList);

                this.list = newList;
                this._messageByList.setState({
                    dataList: [],
                    dataSource: this._messageByList._dataSource.cloneWithRows([]),
                }, ()=>{
                    this._messageByList.setState({
                        dataList: newList,
                        dataSource: this._messageByList._dataSource.cloneWithRows(newList),
                    });
                });

                this.props.navigator.setTabBadge({
                  tabIndex: 0,
                  badge: this.getTotal()>99?'99+':this.getTotal()
                });
            }

            messageArr.push(message);
            let curMess  = _.concat(messageArr, this.props.message[userInfo[0].id]);
            if(curMess && curMess.length > 30){//大于30条时，去掉最久的一条
                await api.post('/message/storemessage',{user_id:userInfo[0].id, logjson:JSON.stringify(_.drop(curMess, 15))});
                curMess = _.dropRight(curMess, 15);
            }

            dispatch(actions.message.message_change(userInfo[0].id, curMess));
        }
    }

    async componentWillMount(){

        this.socket.connect();

        // this.socket.on('connect', () => {
        //     Toast.bottom("服务器连接成功");
        // });

        //获取callback
        this.socket.on('chatevent', (message)=>{
            if(Platform.OS == 'ios'){
                message = JSON.parse(message[0]);
            }else{
                message = message[0];
            }

            this.upDateView(message);
		});
        //设置状态
        this.setRomteState(AppState.currentState);
    }

    componentDidMount() {
        this.onLoad();

        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        this._subcrib = Emitter.addListener('click_message', this._fireMessage.bind(this));

    }

    async onLoad(){
        if(this.state.noData){
            this.setState({ noData: false});
        }

        this._messageByList._pullToRefreshListView.beginRefresh(true);

    }

    componentWillUnmount(){
        this.socket.disconnect();
        if(Platform.OS == 'ios'){//收到推送
             this.subscription && this.subscription.remove();
        }else{
            JPushModule.clearAllNotifications();
        }
        //退出
        this.setRomteState("");
        AppState.removeEventListener('change', this._handleAppStateChange);
        this._subcrib && this._subcrib.remove();
    }

    _onSearchResultListItemPress(rowData){
        // this.props.parent.setState({addressFirst: `${rowData.first_address}${rowData.second_address}`});
    }

    async _getWithdrawList(){
        let list;

        this.setState({ currentPage: 1 });
        list = await api.post('/housekeeper/ownerlistbyreg', {
                       page:1,
                       pagesize: this.pagesize
                    });

       if(Platform.OS == 'ios') {
           this._endWithdrawList(list.data);
       } else {
           setTimeout(() => {
               this._endWithdrawList(list.data);
           }, 100);
       }
    }

    // _updateListView(){
    //     let {actions, dispatch} = this.props;
    //     let action;
    //     if(this.props.status == 1){//收藏地址
    //         action = actions.address.store_change(this.list);
    //     }else {
    //         action = actions.address.history_change(this.list);
    //     }
    //
    //     dispatch(action);
    // }

    async _endWithdrawList(list){

        this.totalpage = list.total_page;
        this.list = list.res;

        if(this.list.length==0){
            this.setState({noData: true});
            return;
        }

        // 初始化消息数据
        let {actions, dispatch} = this.props, idArr=[];
        // idArr = _.map(this.list, 'id');
        for (var i = 0; i < this.list.length; i++) {
            this.unreadMess[i] = 0;
            idArr.push(this.list[i].id);
            dispatch(actions.message.message_init(this.list[i].id));
        }

        let messages = await api.post("/housekeeper/getmessagebyid",{ids:idArr.join(",")});
        if(messages.data && messages.data.length > 0){
            for (var i = 0; i < messages.data.length; i++) {
                let mes1 = messages.data[i].split("&");
                // let mes2 = mes1[1].split(":");
                for (var j = 0; j < mes1.length; j++) {
                    await this.upDateView(JSON.parse(mes1[j]));
                }
            }

        }else {
            // this._updateListView();

            this._messageByList.setState({
                dataList: list.res,
                dataSource: this._messageByList._dataSource.cloneWithRows(list.res)
            });
        }


        this._activityIndicator.setState({ visible: false,});
        this._messageByList._pullToRefreshListView.endRefresh(false);
    }

    async _retrieveNextPage() {

		if (this.state.currentPage != this.totalpage) {
			let page;
            page = this.state.currentPage + 1;
            this.setState({ currentPage: page });

            let list;
            list = await api.post('/housekeeper/ownerlistbyreg', {
                           page:page,
                           pagesize: this.pagesize
                        });

            let {actions, dispatch} = this.props, idArr=[];
        //    const data = this.list;
           const newData = list.data.res;
           newData.map((item, index) => {
               this.unreadMess[this.list.length + index] = 0;
               this.list.push(item);
               idArr.push(item.id);
               dispatch(actions.message.message_init(item.id));
           });

           let messages = await api.post("/housekeeper/getmessagebyid",{ids:idArr.join(",")});
           if(messages.data && messages.data.length > 0){
               for (var i = 0; i < messages.data.length; i++) {
                   let mes1 = messages.data[i].split("&");
                   // let mes2 = mes1[1].split(":");
                   for (var j = 0; j < mes1.length; j++) {
                       await this.upDateView(JSON.parse(mes1[j]));
                   }
               }

           }else{

               this._messageByList.setState({
                   dataList: this.list,
                   dataSource: this._messageByList._dataSource.cloneWithRows(this.list),
               });
           }

           this._messageByList._pullToRefreshListView.endLoadMore(false);

        }else{
            this._messageByList._pullToRefreshListView.endLoadMore(true);
        }
	}

    _onRefresh(){
        this._getWithdrawList();
    }

    _onLoadMore(){
        this._retrieveNextPage();
    }

    _fireMessage(data){
        let {navigator} = this.props;
        let index = _.findIndex(this.list, function(o) { return o.wxOpenId == data.wxOpenId; });
        // let cloneList = [];
        const newList = this.list.map((a, i_index) => {
          //make a copy of the this.list. Otherwise you'll be modifying
          //an object that's in your listView's datasource,
          //and therefore frozen.
          let copyA = {...a};
          if (i_index == index){
            copyA.unread = false;
          }

          return copyA;
        });

        this.unreadMess[index] = 0;

        // this.setState({
        //     unreadMess: this.unreadMess
        // });
        this.list = newList;
        InteractionManager.runAfterInteractions(() => {
            // 暂时这么解决，android不知道咋做
            this._messageByList.setState({
                dataList: [],
                dataSource: this._messageByList._dataSource.cloneWithRows([]),
            }, ()=>{
                this._messageByList.setState({
                    dataList: newList,
                    dataSource: this._messageByList._dataSource.cloneWithRows(newList),
                });
            });

            this.props.navigator.setTabBadge({
              tabIndex: 0,
              badge: this.getTotal()?(this.getTotal()>99?'99+':this.getTotal()):null
            });
        });

        navigator.push({
            title: decodeURIComponent(data.wxName),
            backButtonTitle:'',
            screen: 'housekeeperapp.messageview',
            passProps: {
                userInfo:data
            },
            navigatorStyle:{
                tabBarHidden: true,
                navBarTextColor: 'white',
                navBarButtonColor: 'white',
                navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons:{
                rightButtons:[
                    {
                        title: '电话',
                        icon: require('../../../img/hk_add_phone.png'),
                        id: 'phone',
                    },
                    {
                        title: '新增任务',
                        icon: require('../../../img/hk_add_task.png'),
                        id: 'add',
                    }
                ]
            }
            // backButtonHidden: true,
        });

    }

    getTotal(){
        let total = 0;
        _.forEach(this.unreadMess, function(value, key) {
            total = total + parseInt(value);
        });

        return total;
    }

    _renderRow(rowData, sectionID, rowID){
        // var {tips_openid} = this.state;

        return (
            <Touch onPress={this._fireMessage.bind(this, rowData)}>
                <View style={{marginLeft:15,paddingTop:15,paddingBottom:15,flexDirection: 'row',alignItems:'center',borderBottomWidth: StyleSheet.hairlineWidth, borderColor: "#DEDEDE"}}>
                        {rowData.unread?
                            <View style={styles.headImageBigContainer}>
                                <View style={styles.headUnreadTip}></View>
                                <View style={styles.headImageContainer}>
                                    <Image source={{uri:rowData.wxHeader}} style={styles.headImage}/>
                                </View>
                            </View>:<View style={styles.headImageContainer}>
                                <Image source={{uri:rowData.wxHeader}} style={styles.headImage}/>
                            </View>}
                    <View style={{flex:1, marginLeft:10}}>
                        <Text style={{fontSize: 15, color: '#555555',}}>{decodeURIComponent(rowData.wxName)}</Text>
                        <Text style={{fontSize: 13, color: '#7B7B7B', marginTop: 6, }}>{rowData.homeAddress}</Text>
                    </View>
                </View>
            </Touch>
        );
    }

    _renderNodata(){
        return (
            <View style={{alignItems:'center',justifyContent:'center',flex:1,backgroundColor:'#fff'}}>
                <Image source={require('../../../img/hk_nodata_icon.png')} style={styles.leftImage}/>
                <Text style={{fontSize: 13, color: '#B5B5B5',marginTop:10}}>暂无服务的业主</Text>
            </View>
        );
    }

    render() {
        return (
            this.state.noData?this._renderNodata():
            <View style={styles.container}>
                <CustomListView
                    ref={ (component) => this._messageByList = component }
                    onRefresh={this._onRefresh.bind(this)}
                    onLoadMore={this._onLoadMore.bind(this)}
                    renderRow ={this._renderRow.bind(this)}
                />
                <ListViewActivityIndicator
                    ref={ (component) => this._activityIndicator = component }
                    style={{marginRight: 10, position:'absolute', left: (deviceWidth - 20) / 2, top: (deviceHeight - 64 - 70) / 2, }}
                    color={'#a9a9a9'}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
indexList = connectHelper(state => state)(indexList);

module.exports = indexList;
